//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Common
//  File name:	UnsafeUpdate.cs
//  Developer:	Solomatov Igor
//  Created:	15.04.2012
// 
//  -------------------- iSharePoint -------------------- //

using System.Diagnostics;
using Microsoft.SharePoint;

namespace Smart.Common
{
	/// <summary>
	/// Allow unsafe updates
	/// </summary>
	[DebuggerStepThrough]
	public class UnsafeUpdate : DisposableBase
	{
		protected SPWeb Web;
		protected SPSite Site;

		private readonly bool _savedSiteAuu;
		private readonly bool _savedWebAuu;

		/// <summary>
		/// Allow unsafe updates
		/// </summary>
		public UnsafeUpdate(SPSite site)
		{
			Site = site;

			_savedSiteAuu = site.AllowUnsafeUpdates;

			Site.AllowUnsafeUpdates = true;
		}

		/// <summary>
		/// Allow unsafe updates
		/// </summary>
		public UnsafeUpdate(SPWeb web)
		{
			Web = web;

			_savedWebAuu = web.AllowUnsafeUpdates;

			Web.AllowUnsafeUpdates = true;
		}

		/// <summary>
		/// Allow unsafe updates
		/// </summary>
		public UnsafeUpdate(SPSite site, SPWeb web)
		{
			Site = site;
			Web = web;

			_savedSiteAuu = site.AllowUnsafeUpdates;
			_savedWebAuu = web.AllowUnsafeUpdates;

			Site.AllowUnsafeUpdates = true;
			Web.AllowUnsafeUpdates = true;
		}

		/// <summary>
		/// Dispose managed resources. Method called only once.
		/// </summary>
		protected override void DisposeManaged()
		{
			if (Site != null)
			{
				Site.AllowUnsafeUpdates = _savedSiteAuu;
				Site = null;
			}

			if (Web != null)
			{
				Web.AllowUnsafeUpdates = _savedWebAuu;
				Web = null;
			}
		}

		/// <summary>
		/// Dispose unmanaged resources. Method called only once.
		/// </summary>
		protected override void DisposeUnmanaged()
		{
		}
	}
}